<template>
  <div class="employee-management">
    <!-- 筛选区域 -->
    <div class="filter-container">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-select
            v-model="typeFilter"
            placeholder="请选择员工类型"
            clearable
            @change="handleFilterChange"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="老板" value="BOSS"></el-option>
            <el-option label="经理" value="MANAGEMENT"></el-option>
            <el-option label="员工" value="RECRUITER"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4" v-if="canAddEmployee">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="showAddDialog = true"
          >
            新增员工
          </el-button>
        </el-col>
      </el-row>
    </div>
    <div class="employee-card-list">
      <div
        v-for="(employee, index) in filteredEmployees"
        :key="employee.userId"
        class="employee-card"
        @mouseenter="handleCardHover(index, true)"
        @mouseleave="handleCardHover(index, false)"
        :style="{
          transform: cardHoverStates[index]
            ? 'translateY(-5px)'
            : 'translateY(0)',
        }"
      >
        <!-- 卡片内容（保持不变） -->
        <div class="employee-body">
          <div class="main-content">
            <div class="employee-avatar">
              <el-avatar
                :size="52"
                :src="employee.avatar || defaultAvatar"
                class="avatar-img"
              ></el-avatar>
            </div>

            <div class="employee-info">
              <div class="name-role">
                <h3 class="employee-name">{{ employee.name }}</h3>
                <span class="employee-role">{{ employee.role }}</span>
              </div>

              <div class="meta-info">
                <span class="meta-item type">
                  <el-tag :type="getTypeTagType(employee.type)" size="mini">{{
                    getTypeLabel(employee.type)
                  }}</el-tag>
                </span>
                <span class="meta-item gender">
                  <i
                    :class="
                      employee.gender === 'male'
                        ? 'el-icon-man'
                        : 'el-icon-woman'
                    "
                  ></i>
                  {{ employee.gender === "male" ? "男" : "女" }}
                </span>
                <span class="meta-item age">
                  <i class="el-icon-user"></i>
                  {{ employee.age }}岁
                </span>
                <span class="meta-item location">
                  <i class="el-icon-location-outline"></i>
                  {{ employee.location }}
                </span>
              </div>

              <div class="contact-details">
                <div class="contact-item phone">
                  <i class="el-icon-phone-outline"></i>
                  <span>{{ employee.phone }}</span>
                </div>
                <div class="contact-item date">
                  <i class="el-icon-date"></i>
                  <span>{{ formatDate(employee.birthDate) }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="action-area" v-if="candelete">
            <el-popconfirm
              title="确定要删除该员工吗？"
              @confirm="handleDelete(employee)"
            >
              <el-button
                slot="reference"
                type="danger"
                size="mini"
                class="contact-btn"
              >
                删除
              </el-button>
            </el-popconfirm>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[8, 16, 24]"
        :page-size="pageSize"
        :total="totalEmployees"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </div>

    <el-dialog
      title="新增员工"
      :visible.sync="showAddDialog"
      width="450px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="addEmployeeForm"
        :model="addEmployeeForm"
        :rules="addEmployeeRules"
        label-width="100px"
        class="add-employee-form"
      >
        <el-form-item label="增设方式" prop="employeeCreatedSelect">
          <el-select
            v-model="addEmployeeForm.employeeCreatedSelect"
            placeholder="请选择增设员工的方式"
            style="width: 310px"
            @change="handleCreateTypeChange"
          >
            <el-option label="已有账号" value="0"></el-option>
            <el-option label="新建账号" value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="电话号码" prop="phone">
          <el-input
            v-model="addEmployeeForm.phone"
            placeholder="请输入电话号码"
            maxlength="11"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="密码"
          prop="password"
          v-if="addEmployeeForm.employeeCreatedSelect === '1'"
        >
          <el-input
            v-model="addEmployeeForm.password"
            placeholder="请输入密码"
            type="password"
            show-password
          ></el-input>
        </el-form-item>

        <el-form-item label="员工类型" prop="type">
          <el-select
            v-model="addEmployeeForm.type"
            placeholder="请选择员工类型"
            style="width: 310px"
          >
            <el-option label="管理员" value="MANAGEMENT"></el-option>
            <el-option label="招聘人员" value="RECRUITER"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="员工职位" prop="role">
          <el-cascader
            style="width: 310px"
            v-model="selectedRolePath"
            :options="roleCascaderOptions"
            :props="cascaderProps"
            placeholder="请选择员工职位"
            clearable
            :show-all-levels="false"
            @change="setRoleNameByPath"
          ></el-cascader>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleAddEmployeeSubmit"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCompanyEmployees,
  createEmployee,
  deleteEmployee,
} from "@/api/recuriter/company";
import {
  getAllPositionIndustries,
  getPositionCategoriesByIndustryId,
  getPositionNamesByCategoryId,
} from "@/api/recuriter/position";

export default {
  name: "EmployeeManagement",
  data() {
    return {
      roleCascaderOptions: [],
      selectedRole: [],

      cascaderProps: {
        lazy: true,
        lazyLoad: async (node, resolve) => {
          const { level, value } = node;
          let children = [];

          try {
            if (level === 0) {
              const industryRes = await getAllPositionIndustries();
              if (
                industryRes.data.code === 201 &&
                Array.isArray(industryRes.data.data)
              ) {
                children = industryRes.data.data.map((industry) => ({
                  id: industry.id,
                  name: industry.industryName,
                  leaf: false,
                }));
              }
            } else if (level === 1) {
              const categoryRes = await getPositionCategoriesByIndustryId(
                value
              );
              if (
                categoryRes.data.code === 201 &&
                Array.isArray(categoryRes.data.data)
              ) {
                children = categoryRes.data.data.map((category) => ({
                  id: category.id,
                  name: category.categoryName,
                  leaf: false,
                }));
              }
            } else if (level === 2) {
              const positionRes = await getPositionNamesByCategoryId(value);
              if (
                positionRes.data.code === 201 &&
                Array.isArray(positionRes.data.data)
              ) {
                children = positionRes.data.data.map((position) => ({
                  id: position.id,
                  name: position.detailName,
                  leaf: true,
                }));
              }
            }
          } catch (error) {
            console.error("懒加载数据失败：", error);
          } finally {
            resolve(children);
          }
        },
        label: "name",
        value: "id",
      },
      selectedRolePath: [],

      typeFilter: "",
      genderFilter: "",
      searchKeyword: "",
      roleList: [],
      currentPage: 1,
      pageSize: 8,
      totalEmployees: 0,

      allEmployees: [],
      loading: false,
      cardHoverStates: [],
      selectedEmployee: {},
      defaultAvatar:
        "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",

      // 新增员工相关
      showAddDialog: false,
      addEmployeeForm: {
        employeeCreatedSelect: "", // 新增：增设方式（0-已有账号，1-新建账号）
        phone: "",
        password: "",
        type: "",
        role: "",
      },
      addEmployeeRules: {
        phone: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入有效的11位手机号码",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
            // 动态验证：仅当选择“新建账号”时才校验
            validator: (rule, value, callback) => {
              if (this.addEmployeeForm.employeeCreatedSelect === "1") {
                if (!value) {
                  callback(new Error("请输入密码"));
                } else if (value.length < 4 || value.length > 20) {
                  callback(new Error("密码长度在4-20个字符之间"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
          },
        ],
        type: [
          { required: true, message: "请选择员工类型", trigger: "change" },
        ],
        role: [
          { required: true, message: "请选择员工职位", trigger: "change" },
        ],
      },
    };
  },

  computed: {
    userType() {
      return this.$store.state.recruiter.userInfo?.type || "";
    },
    canAddEmployee() {
      return ["BOSS", "MANAGEMENT"].includes(this.userType);
    },
    candelete() {
      return this.userType === "BOSS";
    },

    // 筛选后的员工列表（分页前）
    filteredEmployeesBeforePage() {
      return this.allEmployees.filter((employee) => {
        if (this.typeFilter && employee.type !== this.typeFilter) {
          return false;
        }

        if (this.searchKeyword) {
          const keyword = this.searchKeyword.toLowerCase();
          return (
            employee.name.toLowerCase().includes(keyword) ||
            employee.userId.toString().includes(keyword) ||
            employee.phone.includes(keyword) ||
            employee.role.toLowerCase().includes(keyword) ||
            employee.location.toLowerCase().includes(keyword)
          );
        }

        return true;
      });
    },
    filteredEmployees() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.filteredEmployeesBeforePage.slice(startIndex, endIndex);
    },
  },

  created() {
    this.cardHoverStates = [];
    this.loadEmployees();
  },

  methods: {
    async loadEmployees() {
      this.loading = true;
      try {
        const response = await getCompanyEmployees();
        if (response.data.code === 201 && Array.isArray(response.data.data)) {
          this.allEmployees = response.data.data;
          this.totalEmployees = response.data.data.length;
          this.cardHoverStates = new Array(this.totalEmployees).fill(false);
        } else {
          this.$message.error("获取员工数据格式错误");
        }
      } catch (error) {
        console.error("获取员工数据失败:", error);
        this.$message.error("获取员工数据失败，请重试");
        this.allEmployees = [];
        this.totalEmployees = 0;
      } finally {
        this.loading = false;
      }
    },

    handleFilterChange() {
      this.currentPage = 1;
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
    },

    handleCurrentChange(page) {
      this.currentPage = page;
    },

    handleCardHover(index, isHover) {
      this.$set(this.cardHoverStates, index, isHover);
    },

    async handleDelete(employee) {
      try {
        let res = await deleteEmployee(employee.userId);
        if (res.data.code === 201) {
          this.$store.commit("recruiter/SET_TOKEN", res.data.data);
          this.loadEmployees();
        }
      } catch (error) {
        this.$message.error("删除失败,请稍后重试");
      }
    },

    getTypeTagType(type) {
      const map = {
        BOSS: "danger",
        MANAGER: "warning",
        EMPLOYEE: "success",
        MANAGEMENT: "warning",
        RECRUITER: "info",
      };
      return map[type] || "info";
    },

    getTypeLabel(type) {
      const map = {
        BOSS: "老板",
        MANAGER: "经理",
        EMPLOYEE: "员工",
        MANAGEMENT: "管理层",
        RECRUITER: "招聘人员",
      };
      return map[type] || type;
    },

    formatDate(dateString) {
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    },

    // 新增员工弹窗相关方法
    handleDialogClose() {
      this.showAddDialog = false;
      this.selectedRole = [];
      this.selectedRolePath = [];
      this.$refs.addEmployeeForm && this.$refs.addEmployeeForm.resetFields();
      this.addEmployeeForm.employeeCreatedSelect = "";
    },

    async handleAddEmployeeSubmit() {
      this.$refs.addEmployeeForm.validate(async (valid) => {
        if (valid) {
          try {
            const submitData = { ...this.addEmployeeForm };
            if (submitData.employeeCreatedSelect === "0") {
              delete submitData.password;
            }
            const response = await createEmployee(this.addEmployeeForm);

            if (response.data.code === 201) {
              this.$store.commit("recruiter/SET_TOKEN", response.data.data);
              this.$message.success("员工添加成功");
              this.handleDialogClose();
              this.loadEmployees();
            } else {
              this.$message.error(response.data.message || "添加员工失败");
            }
          } catch (error) {
            console.error("添加员工失败:", error);
            this.$message.error("该账户已注册");
          }
        } else {
          return false;
        }
      });
    },
    async setRoleNameByPath() {
      if (this.selectedRolePath.length !== 3) {
        this.addEmployeeForm.role = "";
        this.$refs.addEmployeeForm?.validateField("role");
        return;
      }

      const [industryId, categoryId, positionId] = this.selectedRolePath;

      try {
        const positionRes = await getPositionNamesByCategoryId(categoryId);
        if (
          positionRes.data.code === 201 &&
          Array.isArray(positionRes.data.data)
        ) {
          const targetPosition = positionRes.data.data.find(
            (item) => item.id === positionId
          );
          this.addEmployeeForm.role = targetPosition
            ? targetPosition.detailName
            : "";
        } else {
          this.addEmployeeForm.role = "";
        }

        this.$nextTick(() => {
          this.$refs.addEmployeeForm?.validateField("role");
        });
      } catch (error) {
        console.error("获取职位名称失败：", error);
        this.addEmployeeForm.role = "";
        this.$refs.addEmployeeForm?.validateField("role");
      }
    },
    handleCreateTypeChange() {
      this.$refs.addEmployeeForm?.clearValidate("password");
      this.addEmployeeForm.password = "";
    },
  },
};
</script>

<style scoped>
.employee-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.filter-container {
  margin-bottom: 16px;
  padding: 12px;
  border-radius: 6px;
}

.pagination-container {
  text-align: right;
  margin-top: 16px;
  padding-top: 8px;
}

.employee-card-list {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 14px;
  margin-bottom: 16px;
}

.employee-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
  padding: 12px 16px;
  transition: all 0.3s ease;
  cursor: pointer;
  height: 100%;
  box-sizing: border-box;
}

.employee-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.main-content {
  display: flex;
  align-items: center;
  gap: 14px;
}

.employee-avatar {
  flex-shrink: 0;
}

.avatar-img {
  border: 2px solid #f0f0f0;
  transition: transform 0.3s ease;
}

.employee-card:hover .avatar-img {
  transform: scale(1.05);
}

.employee-info {
  flex: 1;
  min-width: 0;
}

.name-role {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 6px;
}

.employee-name {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.employee-role {
  font-size: 12px;
  color: #666;
  background-color: #f5f7fa;
  padding: 1px 6px;
  border-radius: 4px;
  white-space: nowrap;
}

.meta-info {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 6px;
}

.meta-item {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.meta-item i {
  font-size: 11px;
}

.meta-item.type {
  background-color: transparent;
}

.meta-item.gender {
  background-color: #f0f7ff;
  color: #1890ff;
}

.meta-item.age {
  background-color: #f6ffed;
  color: #52c41a;
}

.meta-item.location {
  background-color: #fff7e6;
  color: #fa8c16;
}

.contact-details {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.contact-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  color: #666;
}

.contact-item i {
  color: #1890ff;
  font-size: 12px;
}

.contact-item.phone {
  flex: 1;
  min-width: 140px;
}

.action-area {
  display: flex;
  justify-content: end;
  flex-shrink: 0;
  padding-left: 8px;
  margin-top: 5px;
}

.contact-btn {
  margin-right: 10px;
  padding: 4px 12px;
  font-size: 12px;
  transition: all 0.2s ease;
}

.contact-btn:hover {
  transform: translateY(-2px);
}

/* 新增员工表单样式 */
.add-employee-form {
  margin-top: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .employee-card-list {
    grid-template-columns: 1fr;
  }

  .main-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .action-area {
    padding-left: 0;
    margin-top: 10px;
    align-self: flex-end;
  }
}
</style>